//
//  SN_Id_Authentication_ViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/28.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_Id_Authentication_ViewController.h"

@interface SN_Id_Authentication_ViewController ()<UITextFieldDelegate>
{
    UIButton *editBtn;
}

@property (nonatomic, strong) UITextField *idTextField;

@end

@implementation SN_Id_Authentication_ViewController

- (void)loadView {
    
    [super loadView];
    
    [self.view setBackgroundColor:colorFromHex(@"F4F5F7")];
    
    self.navBar.navigationItem.title = @"实名认证";
    
    editBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [editBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [editBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [editBtn setTitle:@"验证" forState:(UIControlStateNormal)];
    [editBtn setTitleColor:colorFromHex(@"ffffff") forState:(UIControlStateNormal)];
    [editBtn addTarget:self action:@selector(makeSure) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem *makeItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    
    [self.navBar.navigationItem setRightBarButtonItem:makeItem];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [backBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [backBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [backBtn setTitle:@"退出" forState:(UIControlStateNormal)];
    [backBtn setTitleColor:colorFromHex(@"ffffff") forState:(UIControlStateNormal)];
    [backBtn addTarget:self action:@selector(disMissVC) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    self.navBar.navigationItem.leftBarButtonItem = backItem;
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(15, SafeAreaTopHeight+14, 16, 16)];
    [img setImage:[UIImage imageNamed:@"叹号"]];
    [self.view addSubview:img];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(img.right+2, 12+SafeAreaTopHeight, SCREENWIDTH - 30 - 16 -2, 55)];
    [lab setFont:[UIFont systemFontOfSize:15]];
    [lab setText:@"为确认您的家长身份，请完成实名认证，完成验证后可获得查看答案特权，我们会严格保密所有资料。"];
    lab.numberOfLines = 0;
    lab.lineBreakMode = NSLineBreakByWordWrapping;
    [lab setTextColor:colorFromHex(@"979797")];
    [self.view addSubview:lab];
    
    [self.view addSubview:self.idTextField];
    
    [self.idTextField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)disMissVC {
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:@"api_user_logout" forKey:@"method"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSUserDefaults *udd=[NSUserDefaults standardUserDefaults];
        
        [udd removeObjectForKey:@"mobile"];
        [udd removeObjectForKey:@"token"];
        [udd removeObjectForKey:@"userid"];
        [udd removeObjectForKey:XZHEADURL];
        [udd removeObjectForKey:@"isLogin"];
        [udd synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:@"网络异常，请稍后重试！"];
    }];
    
}

- (void)makeSure {
    
    if (![self accurateVerifyIDCardNumber:self.idTextField.text]) {
        [Utils alertViewWithMessage:@"请输入正确的身份证号码"];
        
        return;
    }
    
    int year = [[self.idTextField.text substringWithRange:NSMakeRange(6, 4)] intValue];
    NSString *month = [self.idTextField.text substringWithRange:NSMakeRange(10, 4)];
    
    int valueDate = [[NSString stringWithFormat:@"%d%@",(year+18),month] intValue];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMdd"];
    int today = [[formatter stringFromDate:[NSDate date]] intValue];
    
    if (today < valueDate) {
        
        [Utils alertViewWithMessage:@"您的年龄尚未达到要求，暂不开放"];
        
        return;
    }
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    [param setObject:@"api_user_setcardid" forKey:@"method"];
    [param setObject:USERID forKey:@"userid"];
    [param setObject:self.idTextField.text forKey:@"cardid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
       
        [self showHint:@"认证成功"];
        
        NSDictionary *imformation = [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID];
        NSDictionary * userinfo = [imformation objectForKey:@"userinfo"];
        NSMutableDictionary *informationM = [NSMutableDictionary dictionaryWithDictionary:imformation];
        NSMutableDictionary *userinfoM = [NSMutableDictionary dictionaryWithDictionary:userinfo];
        
        [userinfoM setObject:self.idTextField.text forKey:@"cardid"];
        
        [informationM setObject:@"1" forKey:@"ishavecardid"];
        [informationM setObject:userinfoM forKey:@"userinfo"];

        [SyUserInfomation personalImformationSaveWtih:informationM];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}


//身份证格式判断
- (BOOL)accurateVerifyIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length =0;
    if (!value) {
        return NO;
    }else {
        length = (int)value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}
#pragma mark - Get

- (UITextField *)idTextField {
    
    if (_idTextField == nil) {
        _idTextField = [[UITextField alloc]initWithFrame:CGRectMake(15+30+60, SafeAreaTopHeight+62+20, SCREENWIDTH, 44)];
        _idTextField.textColor = colorFromHex(@"3b3b3b");
        _idTextField.placeholder = @"请输入身份证号";
        _idTextField.delegate = self;
        _idTextField.font = [UIFont systemFontOfSize:16];
        [_idTextField setBackgroundColor:[UIColor whiteColor]];
        
        UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, 64+62+20, SCREENWIDTH, 44)];
        [bg setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:bg];
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 62, 44)];
        [lab setFont:[UIFont systemFontOfSize:15]];
        [lab setText:@"身份证号"];
        [lab setTextColor:colorFromHex(@"3b3b3b")];
        [bg addSubview:lab];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 64+44+62+20, SCREENWIDTH, 0.5)];
        [line setBackgroundColor:colorFromHex(@"979797")];
        //[self.view addSubview:line];
    }
    return _idTextField;
}

@end
